package com.jctrip.hotel.management.util;

import com.google.common.io.BaseEncoding;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtil {

    //签名私钥
    private static String Key = "zjjctrip";
    //签名的失效时间
    private static Long Ttl = 14400000L;


    /**
     * 设置认证token
     * id:登录用户id
     * subject：登录用户名
     */
    public static String createJwt(String id, String name, Map<String, Object> map) {
        // 1.设置失效时间 当前毫秒
        long now = System.currentTimeMillis();
        long exp = now + Ttl;
        // 2.创建jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, generalKey());
        // 3.根据map设置claims
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(), entry.getValue());
        }
        jwtBuilder.setExpiration(new Date(exp));
        //4.创建token
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 验证token
     *
     * @return
     */
    public static boolean checkToken(String token) {
        try {
            log.info("token= {}", token);
            Jwts.parser().setSigningKey(generalKey()).parseClaimsJwt(token);
            return true;
        } catch (SecurityException | MalformedJwtException e) {
            log.info("Invalid JWT signature.");
            e.printStackTrace();
        } catch (ExpiredJwtException e) {
            log.info("Expired JWT token.");
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            log.info("Unsupported JWT token.");
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            log.info("JWT token compact of handler are invalid.");
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 解析token字符串获取clamis
     */
    public static Claims parseJwt(String token) {
        Claims claims = Jwts.parser().setSigningKey(generalKey()).parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * 由字符串生成加密key
     *
     * @return SecretKey
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = BaseEncoding.base64().decode(Key);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "HmacSHA256");
        return key;
    }
}
